<?php

class SearchApp extends MallbaseApp
{
    private $_goods_mod;
    private $_store_mod; 
    private $_gcategory_mod;
    private $_attribute_mod;
    private $_goodsattr_mod;
    private $_scategory_mod;
    private $_sgrade_mod;
    
    protected $page_size = 60;
    protected $source = 'wl_goods';
    protected $words = '';
    private $_totalFound = 0;
    private $_ids = array();

    /* 构造函数 */
    public function __construct()
    {
         $this->SearchApp();
    }

    public function SearchApp()
    {
        parent::__construct();
        
        $this->_goods_mod =& m('goods');
        $this->_store_mod =& m('store');
        $this->_gcategory_mod =& bm('gcategory');
        $this->_attribute_mod =& m('attribute');
        $this->_goodsattr_mod =& m('goodsattr');
        $this->_scategory_mod =& m('scategory');
        $this->_sgrade_mod =& m('sgrade');
    }
    /* 搜索商品 */
    public function index()
    { 
        // 查询参数
        $params = $this->_get_query_param();
        if (isset($params['cate_id']) && $params['layer'] === false)
        {
            $this->show_warning('no_such_category');
            return;
        }
        /* 筛选条件 */
        $this->assign('filters', $this->_get_filter($params));

        /* 分页信息 */
        $page = $this->_get_page($this->page_size);      
        $params['limit'] = $page['limit'];
        
        /* 排序 */
        $order_arr = $this->_get_goods_orders();
        $order_tmp =  isset($_GET['order']) && isset($order_arr[$_GET['order']])? $order_arr[$_GET['order']] : '';
        $this->assign('orders', trim($_GET['order']));
        
        //获取分类信息
        $cate_id = isset($params['cate_id']) ? $params['cate_id'] : 0;
        $gcategory_list = $this->_get_one_gcategory($cate_id,$this->_list_gcategory());
        $params['cate_ids'] = $this->_get_cate_child_ids($cate_id, $gcategory_list);
        
        /* 商品列表 */
        $conditions = $this->_get_goods_conditions($params);
        $order = $order_tmp ? $order_tmp : ($this->_ids ? "FIELD(g.goods_id," . implode(",", $this->_ids) . ")" : 'g.add_time desc');
        $goods_list = $this->_goods_mod->find(array(
            'conditions' => $conditions,
            'fields'     => 'g.store_id, g.goods_name, g.start_stock, g.cate_id, g.price, g.is_hot, g.default_image, g.brand, g.promote_price , g.shipping_id, g.act_id, s.store_name',
            'join'       => 'belongs_to_store, has_goodsstatistics',  
            'order'      => $order,
            'count'      => true,
            'limit'      => $page['limit'],
        ));

        if($goods_list)
        {
            foreach ($goods_list as $key => $val)
            {
                if($val['act_id'] > 0)
                {
                    $act_ids[$val['act_id']] = $val['act_id'];
                }

            }

            if($act_ids)
            {
                $activity_model =& m('activity');
                $activity_list = $activity_model->_get_activity_list($act_ids);//获取参与活动的商品活动数据
            }

            foreach ($goods_list as $key => $goods)
            {
                empty($goods['default_image']) && $goods_list[$key]['default_image'] = Conf::get('default_goods_image');
                if(isset($activity_list[$goods['act_id']]))
                {
                    $goods_list[$key]['act_name'] = $activity_list[$goods['act_id']]['act_name'];
                    $goods_list[$key]['free_shipping'] = $activity_list[$goods['act_id']]['free_shipping'];
                    $goods_list[$key]['is_promotion'] = 1;
                }
            }
        }

        $page['item_count'] = $this->_totalFound ? $this->_totalFound : $this->_goods_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);//分页数据
        $this->assign('goods_list', $goods_list);//商品列表

        /*如果是最后一级分类则获取分类的属性*/
        $this->_get_cate_attr($cate_id, $gcategory_list, $params);
        
        $this->assign('curlocal_gcategory', $this->_get_curlocal_gcategory($cate_id));//当前分类所有的上级分类树
        $this->assign('gcategory_list', $gcategory_list);//当前分类的同级分类和子分类树
        $this->assign('all_gcategory_list', $this->_list_gcategory());//所有的商品分类树
        
        //推荐商品
        $recommend_mod =& m('recommend');
        $this->assign('recommended_goods', $recommend_mod->get_recommended_goods(16, 3));
        
        /* 浏览历史 */
        $goods_history = $this->_get_goods_history();
        $this->assign('goods_history',$goods_history);
        /* 我们为您推荐商品获取浏览历史最新一个商品同一级分类的最新的10个商品 */
        $com_list = $this->_get_com_history($goods_history);
        
        $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
        $this->assign('com_list',$com_list);
        $this->assign('param',$params);
        $this->assign('is_leaf',$this->_gcategory_mod->is_leaf($cate_id));
        $this->assign('search_type',$_GET['act']);
        $this->assign('search_keyword',$keyword);
        
        if(is_array($this->words)){
            $this->assign('words',  implode('","', array_keys($this->words)));
        }
        /* 配置seo信息 */
        $this->_config_seo($this->_get_seo_info('goods', $cate_id));
        $this->import_resource('indexlist.js');
        $this->display('search.goods.html');
    }
    
    /* 按品牌搜索商品 */
    function brand()
    {
        $this->index();       
    }    
    
    /* 搜索店铺 */
    public function store()
    {
        /* 取得该分类及子分类cate_id */
        $cate_id = empty($_GET['cate_id']) ? 0 : intval($_GET['cate_id']);
        $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
        $cate_ids=array();
        $condition_id='';
        if ($cate_id > 0)
        {
            $cate_ids = $this->_scategory_mod->get_descendant($cate_id);
        }

        /* 店铺分类检索条件 */
        $condition_id=implode(',', $cate_ids);
        $condition_id && $condition_id = ' AND cate_id IN(' . $condition_id . ')';

        /* 其他检索条件 */
        $conditions = $keyword ? " AND store_name LIKE '%{$keyword}%'" : "";

        //$regions = $this->_store_mod->list_regions();
        $page   =   $this->_get_page(10);   //获取分页信息
//        $stores = $this->_store_mod->findAll(array(
//            'fields'=> 's.store_name,s.owner_name,s.im_qq,s.im_ww,s.store_logo',
//            'conditions'  => 'state = ' . STORE_OPEN . $condition_id . $conditions,
//            'limit'   =>$page['limit'],
//            'order'   => empty($_GET['order']) || !in_array($_GET['order'], array('credit_value desc')) ? 'recommended desc ,sort_order' : $_GET['order'],
//            'count'   => true   //允许统计
//        ));
        $condition = 'g.goods_id is not null AND g.closed = 0 AND g.if_show = 1 AND s.state = ' . STORE_OPEN . $condition_id . $conditions;
        
        $order = empty($_GET['order']) || !in_array($_GET['order'], array('credit_value desc')) ? 's.recommended desc ,s.sort_order, s.store_id' : $_GET['order'];
        $sql = "select distinct s.store_id,s.store_name,s.owner_name,s.im_qq,s.im_ww,s.store_logo from wl_store s  
                left join wl_goods g on s.store_id=g.store_id where "  . $condition . " order by {$order} limit {$page['limit']}";
                
        $stores = $this->_store_mod->getAll($sql);
        foreach ($stores as $key => $store)
        {
            //店铺logo
            empty($store['store_logo']) && $stores[$key]['store_logo'] = Conf::get('default_store_logo');

            //商品数量
            //$stores[$key]['goods_count'] = $this->_goods_mod->get_count_of_store($store['store_id']);

            //等级图片
//            $step = intval(Conf::get('upgrade_required'));
//            $step < 1 && $step = 5;
//            $stores[$key]['credit_image'] = $this->_view->res_base . '/images/' . $this->_store_mod->compute_credit($store['credit_value'], $step);
            $stores[$key]['goods'] = $this->_goods_mod->find(array(          
                'fields'=> 'goods_id, goods_name, default_image, price',
                'conditions' => 'closed = 0 AND if_show = 1 AND store_id = ' . $store['store_id'],
                'count' => true,
                'order' => 'add_time DESC',
                'limit' => 5,
            ));
            foreach ($stores[$key]['goods'] as $k => $goods)
            {
                empty($goods['default_image']) && $stores[$key]['goods'][$k]['default_image'] = Conf::get('default_goods_image');
            }

        }
        
        $countsql = "select count(distinct s.store_id) from wl_store s left join wl_goods g on s.store_id=g.store_id where " . $condition;
        $page['item_count']= $this->_store_mod->getOne($countsql);   //获取统计数据
        $this->_format_page($page);

        /* 当前位置 */
        $this->_curlocal($this->_get_store_curlocal($cate_id));
        //$scategorys = $this->_list_scategory();
        $this->import_resource('indexlist.js');
        $this->assign('stores', $stores);
        //$this->assign('regions', $regions);
        $this->assign('cate_id', $cate_id);
        //$this->assign('scategorys', $scategorys);
        $this->assign('page_info', $page);
        $this->assign('search_type',$_GET['act']);
        $this->assign('search_keyword',$keyword);
        /* 配置seo信息 */
        $this->_config_seo($this->_get_seo_info('store', $cate_id));
        $this->display('search.store.html');
    }
    
    
    private function _get_goods($params)
    {
        $ids = array();
        $totalFound = 0;
        if (!empty($params['keyword'])) {
            require ROOT_PATH . '/includes/sphinx/sphinx.php';
            $sphinx = new Sphinx;
            $param = array();
            $param['filter']['if_show'] = array(1);
            $param['filter']['closed'] = array(0);
            $param['filter']['state'] = array(1);
            if (isset($params['is_hot']))
                $param['filter']['is_hot'] = array($params['is_hot']);
            if (isset($params['cate_ids']) && is_array($params['cate_ids']) && $params['cate_ids'])
                $param['filter']['cate_id'] = $params['cate_ids'];
            if (isset($params['start_stock']) && is_array($params['start_stock']) && $params['start_stock'])
                $param['filterRange']['start_stock'] = $params['start_stock'];
            if (isset($params['price']) && is_array($params['price']) && $params['price'])
                $param['filterFloatRange']['price'] = $params['price'];
            if (isset($params['attr_uni']) && is_array($params['attr_uni']) && $params['attr_uni'])
                $param['filterAnd']['attr_uni'] = $params['attr_uni'];
            $param['weight'] = array(
                'goods_name' => 20,
                'brand' => 10,
                'store_name' => 8,
            );
            $param['sort'] = array(SPH_SORT_EXTENDED, "@weight DESC");
            $param['limit'] = array($params['limit']);
            $result = $sphinx->getSphinx($params['keyword'], $this->source, $param);
            if (isset($result[0]) && isset($result[0]['total']) && $result[0]['total'] > 0) {
                $totalFound = $result[0]['total_found'];
                foreach ($result[0]['matches'] as $val)
                {
                    array_push($ids, $val['id']);
                }
                $this->words = $result[0]['words'];
            }
        }
        return array($totalFound,$ids);
    }


     /* 取得店铺分类 */
    private function _list_scategory()
    {
        $scategories = $this->_scategory_mod->get_list(-1,true);
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($scategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getArrayList(0);
    }
    
    /* 取得商品分类 */
    private function _list_gcategory()
    {
        $cache_server =& cache_server();
        $key = 'search_goods_category';
        $data = $cache_server->get($key);
        if ($data === false)
        {
            $gcategory_mod =& bm('gcategory', array('_store_id' => 0));
            $gcategories = $gcategory_mod->get_list(-1,true);
    
            import('tree.lib');
            $tree = new Tree();
            $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
            $data = $tree->getArrayListWithId(0);

            $cache_server->set($key, $data, 3600);
        }
        return $data;
    }
    
    /**
     *  取得某个商品分类的同级分类与子分类
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品的所有的分类
     *  @return array
     */
    private function _get_one_gcategory($cate_id,$arr=array())
    {
        static $data = null;
        if(!$cate_id || !$arr)
        {
           return ; 
        }       
        if(is_array($arr))
        {
            foreach($arr as $key=>$val)
            {
                if($cate_id == $val['id'])
                {
                    $data['cate'] = $arr;
                    $data['children'] = $val['children'];
                    break;
                }
               else
               {
                 $this->_get_one_gcategory($cate_id,$val['children']);
               }
            }
            
        }       
        return $data;
    }
    
    /**
     *  取得当前商品分类与所有的父级分类
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品的所有的分类
     *  @return array
     */
    private function _get_curlocal_gcategory($cate_id)
    {
        $arr = array();
        $parents = array();
        if ($cate_id)
        {
            $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
        }
        foreach ($parents as $category)
        {
            $data = $this->_get_one_gcategory($category['cate_id'],$this->_list_gcategory());
            $arr[] = array('cate_id' => $category['cate_id'],'cate_name' => $category['cate_name'], 'category' => $data['cate']);
        }
        return $arr;
     }
     
     /**
     *  取得当前商品分类的属性
     *  @author  yanghj 2014.07.16
     *  @param int $cate_id    商品分类ID
     *  @param array $arr      商品分类关联商品的属性
     */
    private function _get_gcategory_attribute($cate_id)
    {   $cate_id = intval($cate_id);
        if($cate_id<1)
        {
            return ;
        }
        $cache_server =& cache_server();
        $key = 'page_category_attribute'.$cate_id;
        $data = $cache_server->get($key);
        if ($data === false)
        {
            $sql = "SELECT attr_id FROM {$this->_attribute_mod->table}  WHERE cate_id = {$cate_id} AND attr_index = 1";
            $attr_ids = $this->_attribute_mod->getCol($sql);
            if($attr_ids)
            {
                $conditions = 'attr_id' . db_create_in($attr_ids).' AND g.if_show = 1 AND g.closed = 0 ';
                $goods_attr = $this->_goodsattr_mod->find(array(
            		'fields'=> 'this.gattr_id,this.attr_name,this.attr_value,this.attr_uni,this.attr_id,this.goods_id',
            		'conditions' => $conditions." GROUP BY attr_value",
                        'index_key' => 'attr_uni',
                        'join' => 'belongs_to_goods',
            		'order' => 'attr_id ASC',
    	     	));

                if($goods_attr)
                {
                    foreach($goods_attr as $key => $val)
                    {
                        $children_key = $val['gattr_id'];
                        
                        if($val['attr_value'] == "其他" || $val['attr_value'] == "其它")
                            $children_key = 0;
            
                        $attr_data[$val['attr_id']]['attr_id']   = $val['attr_id'];
                        $attr_data[$val['attr_id']]['attr_name']  = $val['attr_name'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['attr_value'] = $val['attr_value'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['gattr_id']   = $val['attr_uni'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['goods_id']   = $val['goods_id'];
                        $attr_data[$val['attr_id']]['children'][$children_key]['attr_id']    = $val['attr_id'];     
                        krsort($attr_data[$val['attr_id']]['children']); 
                    }
                    $data['goods_attr'] = $goods_attr;
                    $data['attr_data']  = $attr_data;
                    $cache_server->set($key, $data, 3600);
                    
                }                                               
            }
            
        }
        return $data;
    }   

    private function _get_goods_curlocal($cate_id)
    {
        $parents = array();
        if ($cate_id)
        {
            $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
        }

        $curlocal = array(
            array('text' => LANG::get('all_categories'), 'url' => "javascript:dropParam('cate_id')"),
        );
        foreach ($parents as $category)
        {
            $curlocal[] = array('text' => $category['cate_name'], 'url' => "javascript:replaceParam('cate_id', '" . $category['cate_id'] . "')");
        }
        unset($curlocal[count($curlocal) - 1]['url']);

        return $curlocal;
    }

    private function _get_store_curlocal($cate_id)
    {
        $parents = array();
        if ($cate_id)
        {
            $this->_scategory_mod->get_parents($parents, $cate_id);
        }

        $curlocal = array(
            array('text' => LANG::get('all_categories'), 'url' => url('app=category&act=store')),
        );
        foreach ($parents as $category)
        {
            $curlocal[] = array('text' => $category['cate_name'], 'url' => url('app=search&act=store&cate_id=' . $category['cate_id']));
        }
        unset($curlocal[count($curlocal) - 1]['url']);
        return $curlocal;
    }
    
    /* 取得浏览历史 */
    private function _get_goods_history()
    {
            $goods_mod  =& m('goods');
            $goods_list = array();
            $goods_ids  = ecm_getcookie('goodsBrowseHistory');
            $goods_ids  = $goods_ids ? explode(',', $goods_ids) : array();
            if ($goods_ids)
            {
                    $rows = $goods_mod->find(array(
                    'conditions' => $goods_ids,
                    'fields'     => 'goods_name,default_image,price,cate_id_1',
                    ));
                    foreach ($goods_ids as $goods_id)
                    {
                            if (isset($rows[$goods_id]))
                            {
                                    empty($rows[$goods_id]['default_image']) && $rows[$goods_id]['default_image'] = Conf::get('default_goods_image');
                                    $goods_list[] = $rows[$goods_id];
                            }
                    }
        krsort($goods_list);
            }		
            return $goods_list;
    }

    /**
     * 取得查询参数（有值才返回）
     *
     * @return  array(
     *              'keyword'   => array('aa', 'bb'),
     *              'cate_id'   => 2,
     *              'layer'     => 2, // 分类层级
     *              'brand'     => 'ibm',
     *              'region_id' => 23,
     *              'price'     => array('min' => 10, 'max' => 100),
     *          )
     */
    private function _get_query_param()
    {
        static $res = null;
        if ($res === null)
        {
            $res = array();
    
            // keyword 关键词
            $keyword = isset($_GET['keyword']) ? trim(strip_tags($_GET['keyword'])) : '';
            if ($keyword != '')
            {
                $tmp = str_replace(array(Lang::get('comma'),Lang::get('whitespace'),' '),',', $keyword);
                $keyword = explode(',',$tmp);
                sort($keyword);
                $res['keyword'] = $keyword;
            }
    
            // cate_id 分类
            if (isset($_GET['cate_id']) && intval($_GET['cate_id']) > 0)
            {
                $res['cate_id'] = $cate_id = intval($_GET['cate_id']);
                $res['layer']   = $this->_gcategory_mod->get_layer($cate_id, true);
            }
    
            // attr 属性
            if (isset($_GET['attr_value']))
            {
                $attr = trim(strip_tags($_GET['attr_value']));
                $attr = preg_match('/^[\d\.]+$/',$attr) ? $attr : '';
                $res['attr_value'] = $attr;
                $res['attr_uni'] = array_flip(explode('.', $attr));
                if(isset($res['attr_uni'][0]))
                    unset ($res['attr_uni'][0]);
                $res['attr_uni'] = array_flip($res['attr_uni']);
            }
            
            // start_stock  起订量
            if (!empty($_GET['start_stock']))
            {	
                $start_stock = intval($_GET['start_stock']);
                $res['start_stock'] = array(
                    'max' => $start_stock
                );
            }
            // is_hot  热销商品
            if ($_GET['is_hot']==1)
            {
                $res['is_hot'] = intval($_GET['is_hot']);
            }
    
            // price  价格区间
            if (isset($_GET['price']))
            {
                $arr = explode('-', $_GET['price']);
                $min = abs(floatval($arr[0]));
                $max = abs(floatval($arr[1]));
                if ($min * $max > 0 && $min > $max)
                {
                    list($min, $max) = array($max, $min);
                }
    
                $res['price'] = array(
                    'min' => $min,
                    'max' => $max
                );
            }
        }
        return $res;
    }

    /**
     * 取得过滤条件
     */
    private function _get_filter($param)
    {
        static $filters = null;
        if ($filters === null)
        {
            $filters = array();
            if (isset($param['keyword']))
            {
                $keyword = join(' ', $param['keyword']);
                $filters['keyword'] = array('key' => 'keyword', 'name' => LANG::get('keyword'), 'value' => $keyword);
            }
            
			isset($param['spec_value']) && $filters['spec_value'] = array('key' => 'spec_value', 'name' => LANG::get('attr_value'), 'value' => $param['spec_value']);
			isset($param['start_stock']) && $filters['start_stock'] = array('key' => 'start_stock', 'name' => LANG::get('start_stock'), 'value' => $param['start_stock']['max']);
			//isset($param['is_hot']) && $filters['is_hot'] = array('key' => 'is_hot', 'name' => LANG::get('is_hot'), 'value' => $param['is_hot']);
            if (isset($param['price']))
            {
                $min = $param['price']['min'];
                $max = $param['price']['max'];
                if ($min <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('le') . ' ' . price_format($max));
                }
                elseif ($max <= 0)
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => LANG::get('ge') . ' ' . price_format($min));
                }
                else
                {
                    $filters['price'] = array('key' => 'price', 'name' => LANG::get('price'), 'value' => price_format($min) . ' - ' . price_format($max));
                }
            }
            if(isset($param['attr_value']) && !empty($param['attr_value']) && $param['cate_id']>0)
            {
                $attr = $this->_get_gcategory_attribute($param['cate_id']);
                $goods_attr = $attr['goods_attr'];
                $filter_attr = explode('.', $param['attr_value']);  
                if (!empty($filter_attr))
                {
                    foreach ($filter_attr AS $k => $v)
                    {
                        if (is_numeric($v) && $v !=0 &&isset($goods_attr[$v]))
                        {
                            $filters['attr_value'][] = array('key' => 'attr_value', 'name' => $goods_attr[$v]['attr_value'], 'value' => $goods_attr[$v]['attr_uni'], 'attr_id'=> $goods_attr[$v]['attr_id']);
                        }
                    }
                    
                }
            }
            
        }
            
        return $filters;
    }
    
    /**
     * 取得查询条件语句
     *
     * @param   array   $param  查询参数（参加函数_get_query_param的返回值说明）
     * @return  string  where语句
     */
    private function _get_goods_conditions($param)
    {
        /* 组成查询条件 */
        $conditions = " g.if_show = 1 AND g.closed = 0 AND s.state = 1"; // 上架且没有被禁售，店铺是开启状态,
        /*关键词查询*/
        if (isset($param['keyword']))
        {
            //有搜索关键词，用sphinx
            $searchResult = $this->_get_goods($param);
            $this->_totalFound = $searchResult[0];
            $this->_ids = $searchResult[1];
            return "g.goods_id " . db_create_in($this->_ids);
        }
        /*分类查询*/
        if (isset($param['cate_id']))
        {
            $conditions .= " AND g.cate_id_{$param['layer']} = '" . $param['cate_id'] . "'";
        }
        
        /*热销商品查询*/
        if ($param['is_hot']==1)
        {
            $conditions .= " AND g.is_hot = 1";
        }      
        /*起订量查询*/
        if (isset($param['start_stock']))
        {
            $conditions .= " AND g.start_stock <= '" . $param['start_stock']['max'] . "'";
        }
        /*价格查询*/
        if (isset($param['price']))
        {
            $min = $param['price']['min'];
            $max = $param['price']['max'];
            $min > 0 && $conditions .= " AND g.price >= '$min'";
            $max > 0 && $conditions .= " AND g.price <= '$max'";
        }
        /*分类查询*/
        if (isset($param['attr_value']) && !empty($param['attr_value']) && $param['cate_id']>0)
        {
            $attr = $this->_get_gcategory_attribute($param['cate_id']);
            $goods_attr = $attr['goods_attr'];
            $filter_attr = explode('.', $param['attr_value']);
            if (!empty($filter_attr))
            {
                $ext_sql = "SELECT DISTINCT(goods_id) FROM " . $this->_goodsattr_mod->table . " WHERE ";
                $ext_group_goods = array();
    
                foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
                {
                    if (is_numeric($v) && $v !=0 &&isset($goods_attr[$v]))
                    {
                        $sql = $ext_sql . "attr_uni = " . $v;
                        $ext_group_goods = $this->_goodsattr_mod->db->getColCached($sql);
                        $conditions .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id');
                    }
                }
            }
        }
        
        return $conditions;
    }

    /* 商品排序方式 */
    private function _get_orders()
    {
        return array(
            ''                  => Lang::get('select_pls'),
            'sales desc'        => Lang::get('sales_desc'),
            'credit_value desc' => Lang::get('credit_value_desc'),
            'price asc'         => Lang::get('price_asc'),
            'price desc'        => Lang::get('price_desc'),
            'views desc'        => Lang::get('views_desc'),
            'add_time desc'     => Lang::get('add_time_desc'),
        );
    }
    
    /* 商品排序方式 */
    private function _get_goods_orders()
    {
        return array(
            'sales-desc'        => 'sales desc',
            'sales-asc'         => 'sales asc',
            'price-asc'         => 'g.price asc',
            'price-desc'        => 'g.price desc',
            'add_time-desc'     => 'g.add_time desc',
            'add_time-asc'      => 'g.add_time asc',
        );
    }
    
    private function _get_seo_info($type, $cate_id)
    {
        $seo_info = array(
            'keywords'    => '艺术摆件,仿真花饰,餐饮用具,家居用品,特色家具',
            'description' => '万菱家饰网提供各种艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具，款式风格选择多，促销优惠最贴心。'
        );
        switch ($type)
        {
            case 'goods':   
                if ($cate_id)
                {
                    $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
                    $parents = array_reverse($parents);
                    foreach ($parents as $key => $cate)
                        $seo_info['title'] .= $cate['cate_name'] . '-';                    
                    $seo_info['title'] .= Conf::get("site_name");
                }else
                    $seo_info['title'] = '搜索商品-艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具-'.Conf::get("site_name");
                break;
            case 'store':
                $seo_info['title'] = '搜索店铺-艺术摆件、仿真花饰、餐饮用具、家居用品、特色家具-'.Conf::get("site_name");
        }
        /*$parents = array(); // 所有父级分类包括本身
        switch ($type)
        {
            case 'goods':                
                if ($cate_id)
                {
                    $parents = $this->_gcategory_mod->get_ancestor($cate_id, true);
                    $parents = array_reverse($parents);
                }
                $filters = $this->_get_filter($this->_get_query_param());
                foreach ($filters as $k => $v)
                {
                    $seo_info['keywords'] .= $v['value']  . ',';
                }
                break;
            case 'store':
                if ($cate_id)
                {
                    $this->_scategory_mod->get_parents($parents, $cate_id);
                    $parents = array_reverse($parents);
                }
        }
        
        foreach ($parents as $key => $cate)
        {
            $seo_info['title'] .= $cate['cate_name'] . ' - ';
            $seo_info['keywords'] .= $cate['cate_name']  . ',';
            if ($cate_id == $cate['cate_id'])
            {
                $seo_info['description'] = $cate['cate_name'] . ' ';
            }
        }
        $seo_info['title'] .= Lang::get('searched_'. $type) . ' - ' .Conf::get('site_title');
        $seo_info['keywords'] .= Conf::get('site_title');
        $seo_info['description'] .= Conf::get('site_title');*/
        return $seo_info;
    }
    
    private function _sort_price($goods_attr)
    {
        $result = $goods_attr ? $goods_attr : array();
        foreach ($result as $key1 => $attr)
        {
            if($attr['attr_name'] == "价格区间"){
                foreach($attr['children'] as $key2 => $val){
                    $attr_value = str_replace("以上", "", $val['attr_value']);
                    $attr_value = explode("-", $attr_value);
                    unset($result[$key1]['children'][$key2]);
                    $result[$key1]['children'][$attr_value[0]] = $val;
                    ksort($result[$key1]['children']);
                }
            }
        }
        return $result;
    }
    
    private function _get_cate_child_ids($cate_id, $gcategory_list)
    {
        $result = array();
        if(!$cate_id || !$gcategory_list)
        {
            return $cate_id ? array($cate_id) : $result;
        }
        if(isset($gcategory_list['cate'][$cate_id]['children'])){
            $result = array_keys($gcategory_list['cate'][$cate_id]['children']);
            foreach($result as $key){
                if(isset($gcategory_list['cate'][$cate_id]['children'][$key]['children'])){
                    $result = array_merge($result, array_keys($gcategory_list['cate'][$cate_id]['children'][$key]['children']));
                }
            }
            array_push($result, $cate_id);
        }
        return $result;
    }
    
    private function _get_cate_attr($cate_id, $gcategory_list, $params)
    {
        if(empty($gcategory_list['children']))
        {
            $attr_value = '';
            $goods_attr = $this->_get_gcategory_attribute($cate_id);
            if(isset($params['attr_value']))
            {
                $attr_value = $params['attr_value'];
            }
            else
            {
                $attr_count = count($goods_attr['attr_data']);
                for($i=1;$i<=$attr_count;$i++)
                {
                    if($i==$attr_count)
                    {
                        $attr_value .= '0';
                    }
                    else
                    {
                        $attr_value .= '0.';
                    }
                    
                }
            }
            $goods_attr['attr_data'] = $this->_sort_price($goods_attr['attr_data']);
            $this->assign('goods_attr',$goods_attr['attr_data']);//分类的属性
            $this->assign('attr_value',$attr_value);//分类的属性
        }
    }
    
    private function _get_com_history($goods_history)
    {
        $result = array();
        $parent_id = $goods_history[0]['cate_id_1'];
        if($parent_id){
            $result = $this->_goods_mod->find(array(
                        'fields'=> 'goods_id,goods_name,price,cate_id,default_image',
                        'conditions' => "if_show = 1 AND closed = 0 AND state = 1 AND  cate_id_1= " .$parent_id,
                        'order'      => " goods.add_time desc",
                        'join'       => 'belongs_to_store',
                        'limit'      => "10",
                ));
        }
        
        return $result;
    }
    
    private function test()
    {
            $array = array(//abcdefghijklmnopqrstuvwxyz
                'a' => 10, 'b' => 11,'c' => 12, 'd' => 13,'e' => 14, 'f' => 15,'g' => 16, 'h' => 17,
                'i' => 18, 'j' => 19,'k' => 20, 'l' => 21,'m' => 22, 'n' => 23,'o' => 24, 'p' => 25,
                'q' => 26, 'r' => 27,'s' => 28, 't' => 29,'u' => 30, 'v' => 31,'w' => 32, 'x' => 33,
                'y' => 34, 'z' => 35
            );
            $goods_attr = $this->_goodsattr_mod->find(array(
                    'conditions' => " attr_uni = 0",
                    'fields'=> 'attr_value',
                    'limit' => 1000
                ));
            foreach($goods_attr as $id => $v)
            {
                $md5 = md5($v['attr_value']);
                $uni = substr($md5, 0, 2) . substr($md5, -3, 3);
                $result = "";
                for($i = 0; $i<  strlen($uni) ; $i++){
                    if($uni{$i} && !intval($uni{$i})){
                        $result .= $array[$uni{$i}];
                    }else{
                        $result .= $uni{$i};
                    }
                }
                $this->_goodsattr_mod->edit($id, array('attr_uni' => $result));
            }
            
    }
}

?>
